package com.github.catvod.spider;

import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;

import com.github.catvod.crawler.Spider;
import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.utils.SpiderJson;
import com.github.catvod.utils.SpiderUtil;
import com.github.catvod.utils.okhttp.OKCallBack;
import com.github.catvod.utils.okhttp.OkHttpUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;

/**
 * @Author zlliu
 * @Date 2025/7/9
 * @Description
 */
public class QQCartoonBak extends Spider {
    private static final String siteUrl = "https://v.qq.com/";
    private static final String siteHost = "v.qq.com";

    private List<String> typeList = List.of("动漫");

    //  播放源配置
    private JSONObject playerConfig;

    private JSONArray filterArray;

    //  分类页URL规则
    private Pattern regexCategory = Pattern.compile("/channel/(cartoon|tv)");
    //  详情页URL规则
    private Pattern regexVid = Pattern.compile("/(\\w+/\\w+/\\w+)/");
    //  播放页URL规则
    private Pattern regexPlay = Pattern.compile("(/\\w+/\\w+/\\w+/play-\\d+-\\d+.html)");

    //  动漫筛选
    private String cartoonFilterStr = "{\"100119\":[{\"key\":\"iarea\",\"name\":\"地区\",\"value\":[{\"n\":\"全部\",\"v\":\"-1\"},{\"n\":\"内地\",\"v\":\"1\"},{\"n\":\"日本\",\"v\":\"2\"}]},{\"key\":\"itype\",\"name\":\"类型\",\"value\":[{\"n\":\"全部\",\"v\":\"-1\"},{\"n\":\"玄幻\",\"v\":\"9\"},{\"n\":\"科幻\",\"v\":\"4\"}]}]}";
    //  电视剧筛选
    private String tvFilterStr = "{\"100113\":[{\"key\":\"iarea\",\"name\":\"地区\",\"value\":[{\"n\":\"全部\",\"v\":\"-1\"},{\"n\":\"内地\",\"v\":\"0\"},{\"n\":\"香港\",\"v\":\"14\"}]},{\"key\":\"itype\",\"name\":\"类型\",\"value\":[{\"n\":\"全部\",\"v\":\"-1\"},{\"n\":\"爱情\",\"v\":\"1\"},{\"n\":\"古装\",\"v\":\"6\"}]}]}";

    @Override
    public void init(Context context) throws Exception {
        super.init(context);
        try {
            playerConfig = new JSONObject("{\"byun\":{\"sh\":\"云播B线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"dphd\":{\"sh\":\"云播A线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"cyun\":{\"sh\":\"云播C线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"dbm3u8\":{\"sh\":\"云播D线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"i8i\":{\"sh\":\"云播E线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"m3u8hd\":{\"sh\":\"云播F线\",\"pu\":\"https://auete.com/api/?url=\",\"sn\":1,\"or\":999},\"languang\":{\"sh\":\"云播G线\",\"pu\":\"https://auete.com/api/?url=\",\"sn\":1,\"or\":999},\"hyun\":{\"sh\":\"云播H线\",\"pu\":\"https://auete.com/api/?url=\",\"sn\":1,\"or\":999},\"kyun\":{\"sh\":\"云播K线\",\"pu\":\"https://auete.com/api/?url=\",\"sn\":1,\"or\":999},\"bpyueyu\":{\"sh\":\"云播粤语\",\"pu\":\"\",\"sn\":0,\"or\":999},\"bpguoyu\":{\"sh\":\"云播国语\",\"pu\":\"\",\"sn\":0,\"or\":999},\"lyun\":{\"sh\":\"云播L线\",\"pu\":\"https://auete.com/api/?url=\",\"sn\":1,\"or\":999},\"myun\":{\"sh\":\"云播M线\",\"pu\":\"\",\"sn\":0,\"or\":999},\"dp\":{\"sh\":\"Dplayer\",\"pu\":\"\",\"sn\":0,\"or\":999}}");
            filterArray = new JSONArray();
            filterArray.put(new JSONObject(cartoonFilterStr));
            filterArray.put(new JSONObject(tvFilterStr));
        } catch (JSONException e) {
            SpiderDebug.log(e);
        }
    }

    /**
     * 获取分类数据 + 首页最近更新视频列表数据
     *
     * https://v.qq.com/channel/tv?listpage=1&channel=tv&sort=18&_all=1
     * https://v.qq.com/channel/cartoon?listpage=1&channel=cartoon&sort=18&_all=1
     *
     * @param filter 是否开启筛选 关联的是 软件设置中 首页数据源里的筛选开关
     * @return
     */
    @Override
    public String homeContent(boolean filter) {
        try {
            Document doc = Jsoup.parse(OkHttpUtil.string(siteUrl, getHeaders(siteUrl)));
            JSONObject result = new JSONObject();
            JSONArray classes = new JSONArray();
            // 把分类的id和名称取出来加到列表里
            classes.put(new JSONObject("{\"type_id\":\"100119\",\"type_name\":\"动漫\"}"));
            classes.put(new JSONObject("{\"type_id\":\"100113\",\"type_name\":\"电视剧\"}"));

            if (filter) {
                result.put("filters", filterArray);
            }
            result.put("class", classes);
            try {
                // 取首页推荐视频列表
                Element homeList = doc.select("div.scroll-content-wrap").get(0);
                Elements list = homeList.children();
                JSONArray videos = new JSONArray();
                for (int i = 0; i < list.size(); i++) {
                    Element vod = list.get(i);
                    String title = vod.selectFirst("span").html();
                    String cover = vod.selectFirst("div img").attr("src");
                    JSONObject v = new JSONObject();
                    v.put("vod_id", title); //  TODO 待修改
                    v.put("vod_name", title);
                    v.put("vod_pic", cover);
                    v.put("vod_remarks", "remark");   //  TODO 影片更新状态：至24集/共40集
                    videos.put(v);
                }
                result.put("list", videos);
            } catch (Exception e) {
                SpiderDebug.log(e);
            }
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    /**
     * 获取分类信息数据
     *
     * @param tid    分类id,对应homeContent返回的class中的type_id
     * @param pg     当前页数
     * @param filter 同homeContent方法中的filter
     * @param extend 筛选参数{k:v, k1:v1}
     * @return
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        try {
            JSONObject result = new JSONObject();
            String url = "https://pbaccess.video.qq.com/trpc.multi_vector_layout.mvl_controller.MVLPageHTTPService/getMVLPage?&vplatform=2";
            JSONObject queryJson = new JSONObject();
            queryJson.put("channel_id", tid);
            queryJson.put("page_id", "channel_list");
            queryJson.put("page_type", "operation");
            if (extend != null && !extend.isEmpty()) {
                StringBuilder param = new StringBuilder("sort=75");
                for (String key : extend.keySet()) {
                    param.append("&").append(key).append("=").append(extend.get(key));
                }
                queryJson.put("filter_params", param.toString());
            } else {
                queryJson.put("filter_params", "sort=75");
            }
            JSONObject requestJson = new JSONObject();
            requestJson.put("page_params", queryJson);
            OkHttpUtil.postJson(OkHttpUtil.defaultClient(), url, requestJson.toString(), getPostHeaders(), new OKCallBack.OKCallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                }
                @Override
                public void onResponse(String response) {
                    try {
                        //  {"ret":20607,"msg":"unknow error."}
                        //  {"ret":35013,"msg":"unknow error."}
                        JsonObject json = SpiderJson.safeObject(response);
                        JsonArray list = json.getAsJsonObject("data")
                                .getAsJsonObject("modules")
                                .getAsJsonObject("normal")
                                .getAsJsonArray("cards").get(0).getAsJsonObject()
                                .getAsJsonObject("children_list")
                                .getAsJsonObject("poster_card")
                                .getAsJsonArray("cards");
                        JSONArray videos = new JSONArray();

                        JSONObject video = null;
                        for (JsonElement element : list) {
                            JsonObject jsonObject = element.getAsJsonObject();
                            JsonObject card = jsonObject.getAsJsonObject("params");

                            video = new JSONObject();
                            //  mcv8hkc8zk8lnov
                            //  点击进入详情页：https://v.qq.com/x/cover/mcv8hkc8zk8lnov/x0036x5qqsr.html
                            video.put("vod_id", card.get("cid"));
                            video.put("vod_name", card.get("title"));
                            video.put("vod_pic", card.get("new_pic_vt"));
                            video.put("vod_remarks", card.get("sub_title"));
                            video.put("vod_year", card.get("year"));

                            videos.put(video);
                        }

                        result.put("list", videos);
                        result.put("pagecount", list.size());
                    } catch (JSONException e) {
                    }
                }
            });
            result.put("page", pg);
            result.put("limit", 20);
            result.put("total", 200);
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    /**
     * 视频详情信息
     *
     * @param ids 视频id
     * @return
     */
    @Override
    public String detailContent(List<String> ids) {
        try {
            // 视频详情url
            String url = siteUrl + "/" + ids.get(0) + "/";
            //System.out.println(url);
            Document doc = Jsoup.parse(OkHttpUtil.string(url, getHeaders(url)));
            JSONObject result = new JSONObject();
            JSONObject vodList = new JSONObject();

            // 取基本数据
            String cover = doc.selectFirst("div.cover a").attr("href");
            String title = doc.selectFirst("div.cover a").attr("title");
            Elements list1 = doc.select("div.message>p");
            String desc = doc.select("div.message>p").get(list1.size() - 1).text();
            String category = "", area = "", year = "", remark = "", director = "", actor = "";
            Elements span_text_muted = doc.select("div.message>p");
            for (int i = 0; i < span_text_muted.size() - 2; i++) {
                Element text = span_text_muted.get(i);
                String info = text.text();
                if (info.contains("分类")) {
                    try {
                        category = text.text().split(": ")[1];
                    } catch (Exception e) {
                        category = "";
                    }
                } else if (info.contains("年份")) {
                    try {
                        year = text.text().split(": ")[1];
                    } catch (Exception e) {
                        year = "";
                    }
                } else if (info.contains("地区")) {
                    try {
                        area = text.text().split(": ")[1];
                    } catch (Exception e) {
                        area = "";
                    }
                } else if (info.contains("影片备注")) {
                    try {
                        remark = text.text().split(": ")[1];
                    } catch (Exception e) {
                        remark = "";
                    }
                } else if (info.contains("导演")) {
                    try {
                        director = text.text().split(": ")[1];
                    } catch (Exception e) {
                        director = "";
                    }
                } else if (info.contains("主演")) {
                    try {
                        actor = text.text().split(": ")[1];
                    } catch (Exception e) {
                        actor = "";
                    }
                }
            }

            vodList.put("vod_id", ids.get(0));
            vodList.put("vod_name", title);
            vodList.put("vod_pic", cover);
            vodList.put("type_name", category);
            vodList.put("vod_year", year);
            vodList.put("vod_area", area);
            vodList.put("vod_remarks", remark);
            vodList.put("vod_actor", actor);
            vodList.put("vod_director", director);
            vodList.put("vod_content", desc);
            //System.out.println(vodList.toString());
            Map<String, String> vod_play = new TreeMap<>(new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    try {
                        int sort1 = playerConfig.getJSONObject(o1).getInt("or");
                        int sort2 = playerConfig.getJSONObject(o2).getInt("or");

                        if (sort1 == sort2) {
                            return 1;
                        }
                        return sort1 - sort2 > 0 ? 1 : -1;
                    } catch (JSONException e) {
                        SpiderDebug.log(e);
                    }
                    return 1;
                }
            });

            // 取播放列表数据
            Elements sources = doc.select("div#player_list>h2");
            //System.out.println(sources.size());
            Elements sourceList = doc.select("div#player_list>ul");
            //System.out.println(sourceList.size());
            for (int i = 0; i < sources.size(); i++) {
                Element source = sources.get(i);
                //System.out.println(sources.text().split("：")[0].split("』")[1]);
                String sourceName = source.text().split("』")[1].split("：")[0];
                boolean found = false;
                for (Iterator<String> it = playerConfig.keys(); it.hasNext(); ) {
                    String flag = it.next();
                    if (playerConfig.getJSONObject(flag).getString("sh").equals(sourceName)) {
                        sourceName = flag;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    continue;
                }
                String playList = "";
                Elements playListA = sourceList.get(i).select("li > a");
                //System.out.println(playListA.size());
                List<String> vodItems = new ArrayList<>();

                for (int j = 0; j < playListA.size(); j++) {
                    Element vod = playListA.get(j);
                    Matcher matcher = regexPlay.matcher(vod.attr("href"));
                    if (!matcher.find()) {
                        continue;
                    }
                    String playURL = matcher.group(1);
                    vodItems.add(vod.text() + "$" + playURL);
                }
                if (vodItems.size() > 0) {
                    playList = TextUtils.join("#", vodItems);
                }

                if (playList.length() == 0) {
                    continue;
                }

                vod_play.put(sourceName, playList);
            }

            if (vod_play.size() > 0) {
                String vod_play_from = TextUtils.join("$$$", vod_play.keySet());
                String vod_play_url = TextUtils.join("$$$", vod_play.values());
                vodList.put("vod_play_from", vod_play_from);
                vodList.put("vod_play_url", vod_play_url);
            }
            JSONArray list = new JSONArray();
            list.put(vodList);
            result.put("list", list);
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    /**
     * 获取视频播放信息
     *
     * @param flag     播放源
     * @param id       视频id
     * @param vipFlags 所有可能需要vip解析的源
     * @return
     */
    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) {
        try {
            // 播放页 url
            String url = siteUrl + id;
            Document doc = Jsoup.parse(OkHttpUtil.string(url, getHeaders(url)));
            /*取得script下面的JS变量*/
            Elements e = doc.select("div>script");
            /*循环遍历script下面的JS变量*/
            String player = "";
            String pn = "";
            JSONObject result = new JSONObject();
            for (Element element : e) {
                /*取得JS变量数组*/
                String[] data = element.data().toString().split("var");
                /*取得单个JS变量*/
                for (String variable : data) {
                    /*过滤variable为空的数据*/
                    if (variable.contains("=")) {
                        /*取到满足条件的JS变量*/
                        if (variable.contains("now")) {
                            String[] kvp = variable.split("=");
                            player = kvp[1].replaceAll("\"", "").replaceAll(";", "");
                            if (player.startsWith("base64")) {
                                String[] plist1 = player.split("\\(");
                                String[] plist2 = plist1[1].split("\\)");
                                // 解码
                                player = new String(Base64.decode(plist2[0].getBytes(), Base64.DEFAULT));
                                //byte[] base64Data = Base64.getDecoder().decode(plist2[0]);
                                //player = new String(base64Data, "utf-8");
                            }
                            if (player.startsWith("http")) {
                                result.put("parse", 0);
                                result.put("playUrl", "");
                                result.put("url", player);
                                result.put("header", "");
                            } else if (player.contains("m3u8")) {
                                String finalvideo = "https://datas-s8pwfqdu9yystn90fb----------------cache.haozhansou.com/" + player;
                                result.put("parse", 0);
                                result.put("playUrl", "");
                                result.put("url", finalvideo);
                                result.put("header", "");

                            }
                        }
                        if (variable.contains("pn")) {
                            String[] kvp = variable.split("=");
                            pn = kvp[1].replaceAll("\"", "").replaceAll(";", "");
                        }
                    }
                }
                if (playerConfig.has(pn)) {
                    JSONObject pCfg = playerConfig.getJSONObject(pn);
                    String videoUrl = player;
                    String playUrl = pCfg.getString("pu");
                    result.put("parse", pCfg.getInt("sn"));
                    result.put("playUrl", playUrl);
                    result.put("url", videoUrl);
                    result.put("header", "");
                }
            }
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    /**
     * 搜索
     *
     * @param key
     * @param quick 是否播放页的快捷搜索
     * @return
     */
    @Override
    public String searchContent(String key, boolean quick) {
        try {
            String url = siteUrl + "/search.php?searchword=" + key;
            Document doc = Jsoup.parse(OkHttpUtil.string(url, getHeaders(url)));
            JSONObject result = new JSONObject();

            JSONArray videos = new JSONArray();
            Elements list = doc.select("div.card-body>ul>li.media");
            for (int i = 0; i < list.size(); i++) {
                Element vod = list.get(i);
                String title = vod.select("div.media-body>div.subject>a>span").text();
                String cover = "";
                String remark = vod.selectFirst("div.media-body>div.d-flex>div.text-muted>span").text();
                Matcher matcher = regexVid.matcher(vod.select("div.media-body>div.subject>a").attr("href"));
                if (!matcher.find()) {
                    continue;
                }
                String id = matcher.group(1);
                JSONObject v = new JSONObject();

                // 视频封面
                String vodurl = siteUrl + "/" + id + "/";
                Document voddoc = Jsoup.parse(OkHttpUtil.string(vodurl, getHeaders(vodurl)));
                cover = voddoc.selectFirst("div.cover a").attr("href");

                v.put("vod_id", id);
                v.put("vod_name", title);
                v.put("vod_pic", cover);
                v.put("vod_remarks", remark);
                videos.put(v);
            }

            result.put("list", videos);
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

//    @Override
//    public String homeContent(boolean filter) {
//        try {
//            Document doc = Jsoup.parse(OkHttpUtil.string(siteUrl, getHeaders(siteUrl)));
//            // 分类节点
//            Elements elements = doc.select("div[data-mvp-dom='mvp_left_nav']> div a");
//            JSONArray classes = new JSONArray();
//            for (Element ele : elements) {
//                Matcher mather = regexCategory.matcher(ele.attr("href"));
//                if (mather.find()) {
//                    //  business_id=web&mod_id=channel_item&mod_title=左侧导航栏
//                    //  &pgid=page_home_channel&play_scene=material_player&remark=&status=0
//                    //  &title=动漫&ztid=100119&ztname=首页
//                    String params = ele.attr("dt-params");
//                    params = URLDecoder.decode(params, "UTF-8");
//                    JSONObject obj = new JSONObject();
//                    Arrays.stream(params.split("&")).map(param -> param.split("="))
//                            .forEach(array -> {
//                                try {
//                                    obj.put(array[0], array[1]);
//                                } catch (JSONException e) {
//                                }
//                            });
//                    ;
//                    String id = obj.get("ztid").toString();
//
//                    // 把分类的id和名称取出来加到列表里
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("type_id", id);
//                    jsonObject.put("type_name", "name");
//                    classes.put(jsonObject);
//                }
//            }
//            JSONObject result = new JSONObject();
//            if (filter) {
//                result.put("filters", filterArray);
//            }
//            result.put("class", classes);
//            try {
//                // 取首页推荐视频列表
//                Element homeList = doc.select("div.scroll-content-wrap").get(0);
//                Elements list = homeList.children();
//                JSONArray videos = new JSONArray();
//                for (int i = 0; i < list.size(); i++) {
//                    Element vod = list.get(i);
//                    String title = vod.selectFirst("span").html();
//                    String cover = vod.selectFirst("div img").attr("src");
//                    JSONObject v = new JSONObject();
//                    v.put("vod_id", i); //  TODO 待修改
//                    v.put("vod_name", title);
//                    v.put("vod_pic", cover);
//                    v.put("vod_remarks", "remark");   //  TODO 影片更新状态：至24集/共40集
//                    videos.put(v);
//                }
//                result.put("list", videos);
//            } catch (Exception e) {
//                SpiderDebug.log(e);
//            }
//            return result.toString();
//        } catch (Exception e) {
//            SpiderDebug.log(e);
//        }
//        return "";
//    }

    protected HashMap<String, String> getPostHeaders() {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headers.put("User-Agent", SpiderUtil.CHROME);
        headers.put("Accept-Language", "zh-CN,zh;q=0.8");
        headers.put("Cookie", "qq_domain_video_guid_verify=b00e1d1f9a26eda3; _qimei_uuid42=1970d0c311610053f6f148ee8a4365ca9efd8ee87d; _qimei_fingerprint=7ac54314555b80d3430d979145736ea0; _qimei_h38=fded3b66f6f148ee8a4365ca02000007c1970d; pgv_info=ssid=s6537241576; pgv_pvid=3494636352; video_platform=2; video_guid=b00e1d1f9a26eda3; _qimei_q32=abc071801dc6ce70ff9a29f05a057207; _qimei_q36=19ff59be5170bcd473406d94300010417c05; QIMEI32=abc071801dc6ce70ff9a29f05a057207; QIMEI36=19ff59be5170bcd473406d94300010417c05; vdevice_qimei36=19ff59be5170bcd473406d94300010417c05; yyb_muid=30C76B12C03B63A005BA7D3AC13A62C5; video_omgid=b00e1d1f9a26eda3");
        return headers;
    }

    protected HashMap<String, String> getHeaders(String url) {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("method", "GET");
        headers.put("Host", siteHost);
        headers.put("Upgrade-Insecure-Requests", "1");
        headers.put("DNT", "1");
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        headers.put("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        return headers;
    }

}
